package com.ty.springbootweb;

import jakarta.annotation.Resource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.WebApplicationContext;

/**
 * UserControllerTester
 *
 * @aurhor Administrator  whs
 * @since 2024/9/5
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTester {

    @Resource
    private WebApplicationContext wac;  // 注入Spring Web 上下文的环境
    private MockMvc mockMvc;

    @Before // 提前加载内容
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void testGetUser() throws Exception {  // 根据id查询数据
        String mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/user/2")).andReturn().getResponse().getContentAsString();
        System.out.println("\n\nResult === " + mvcResult);
    }

    @Test
    public void testAddUser() throws Exception { // 测试添加
        final MultiValueMap<String,String> params = new LinkedMultiValueMap<>();
        params.add("usrName", "egdh ");
        params.add("usrPassword", "66666");
        params.add("usrRoleId", "2");
        params.add("usrFlag", "1");
        mockMvc.perform(MockMvcRequestBuilders.post("/user/add").params(params))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print());

    }


}
